#!/bin/bash
# /**
# * Copyright (c) 2018, God's harbor
# * All rights reserved.
# * @file    replace_str.sh
# * @brief   替换某个目录下的字符串
# * @author  Jason Zhou,yzfcer@163.com
# * @version 1.0
# * @date    2021-09-15
# */

function usage()
{
    echo "replace_str.sh usage:"
    echo "replace_str.sh <DirOrFile> <oldstr> <newstr>"
}

function check_args()
{
    # echo "$1="$1
    # echo "$#="$#
    if [ $# -lt 3 ]
    then
        usage
        exit
    fi
    if [ "$1" == "-h" ]
    then
        usage
        exit
    fi
}

# function replace_file_type()
# {
#     DIR=$1
#     OLD=$2
#     NEW=$3
#     type=$4
#
#
#     files=$(find ${DIR} -name $type)
#     for file in $files
#     do
#         echo $file
#         sed -i "s/${OLD}/${NEW}/g" ${file}
#     done
# }
#

function main()
{
    # check_args $@
    # FTYPES+=" -name *.h"
    # FTYPES+=" -o -name *.c"
    # FTYPES+=" -o -name *.cpp"
    # FTYPES+=" -o -name *.js"
    # FTYPES+=" -o -name *akefile"
    echo "FTYPES=${FTYPES}"
    # if [ -d ${DIR} ]
    # then
    #     files=$(find ${DIR} ${FTYPES})
    #     for file in $files
    #     do
    #         # echo $file
    #         echo "sed -i 's/${OLD}/${NEW}/g' ${file}"
    #         sed -i "s/${OLD}/${NEW}/g" ${file}
    #     done
    # fi
}

check_args $@
DIR="$1"
OLD="$2"
NEW="$3"
echo "DIR=${DIR}"
echo "OLD=${OLD}"
echo "NEW=${NEW}"

FTYPES+=" -name *.h"
FTYPES+=" -o -name *.c"
FTYPES+=" -o -name *.cpp"
# FTYPES+=" -o -name *.js"
# FTYPES+=" -o -name *akefile"
echo "FTYPES=${FTYPES}"

if [ -d ${DIR} ]
then
    files=$(find ${DIR} ${FTYPES})
    for file in $files
    do
        # echo $file
        echo "sed -i 's/${OLD}/${NEW}/g' ${file}"
        sed -i "s/${OLD}/${NEW}/g" ${file}
    done
fi
